//
//  MyDataController.m
//  HiCar
//
//  Created by huachun on 2019/2/14.
//  Copyright © 2019 丁一. All rights reserved.
//

#import "MyDataController.h"
#import "MyDataViewModel.h"
#import "CenterModel.h"
#import "HiDateView.h"
#import "MyDataCell.h"
#import "CenterAction.h"
#import "HiJonesClass.h"
#import "ChangeUDataVModel.h"
#import "OSSTestMacros.h"
#import "AliyunUploadBlock.h"

@interface MyDataController ()<UINavigationControllerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,ChangeUDataDelegate>{
    NSMutableArray *linarray;
    NSMutableArray *lindeletearray;
    
    UIImage        *Change_img;
    NSString       *lin_im_url;
}

@property (nonatomic, strong) UIButton   *DoneButton;
@property (nonatomic, strong) UserModel  *HereUserModel;
@property (nonatomic, strong) HiDateView *dateview;
@property (nonatomic, strong) UILabel     *Toulabel;

@property (nonatomic, strong) NSMutableArray *newlogoarray;

@property (nonatomic, strong) NSMutableArray *change_logo;

@end

@implementation MyDataController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title=@"编辑资料";
    
    _HereUserModel = [UserModel info];
    
    MyDataViewModel *viewmodel = [[MyDataViewModel alloc] init:@[]];
    self.Data_array = [NSMutableArray new];
    self.Data_array = [viewmodel.dataSource mutableCopy];
    
    [self.view addSubview:self.TableView];
    self.TableView.separatorInset      = UIEdgeInsetsMake(0, 15, 0, 0);
    self.TableView.separatorStyle      = UITableViewCellSeparatorStyleSingleLineEtched;
    self.TableView.separatorColor      = [JonesClass stringTOColor:@"#e9e9e9"];
    self.TableView.backgroundColor = [JonesClass stringTOColor:@"#fbfbfb"];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.TableView reloadData];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [self.Data_array count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 100;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *FootView = [[UIView alloc] init];
    if (section == self.Data_array.count-1) {
        [FootView addSubview:self.DoneButton];
    }
    return FootView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [[self.Data_array objectAtIndex:section] count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CenterModel *model = [[self.Data_array objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    return model.Height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CenterModel * model = [[self.Data_array objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    MyDataCell *cell = [MyDataCell cellForTableView:tableView cellForRowAtIndexPath:indexPath];
    cell.SuperModel=_HereUserModel;
    cell.Model = model;
    if ([model.Tittle isEqualToString:@"头像"]){
        if (Change_img) {
            cell.Img.image = Change_img;
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CenterModel * model = [[self.Data_array objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    if ([model.Tittle isEqualToString:@"昵称"]) {
        [CenterAction Actiontodone:JonesGOTO_CenterName view:self dictionary:@{@"type":@"1",@"model":_HereUserModel}];
    }else if ([model.Tittle isEqualToString:@"年龄"]){
        [self setview];
    }else if ([model.Tittle isEqualToString:@"头像"]){
        [self clickImge];
    }else if ([model.Tittle isEqualToString:@"密码"]){
        [CenterAction Actiontodone:JonesGOTO_CenterPassward view:self dictionary:@{@"model":_HereUserModel}];
    }else if ([model.Tittle isEqualToString:@"性别"]){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"选择性别" preferredStyle: UIAlertControllerStyleActionSheet];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"男士" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            self->_HereUserModel.sex = @"False";
            [self.TableView reloadData];
        }];
        UIAlertAction *archiveAction = [UIAlertAction actionWithTitle:@"女士" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            self->_HereUserModel.sex = @"True";
            [self.TableView reloadData];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:deleteAction];
        [alertController addAction:archiveAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)setview{
    __weak __typeof(&*self)weakSelf = self;
    if (!_dateview) {
        _dateview = [[HiDateView alloc] initWithFrame:CGRectMake(0, RECERHEIGHT, RECRWITCH, 270) type:0];
        _dateview.selectblock = ^(NSString * _Nonnull date, NSDate * _Nonnull userdate) {
            NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
            [dateformatter setDateFormat:@"yyyy-MM-dd"];
            NSString *dateStr = [dateformatter stringFromDate:userdate];
            self->_HereUserModel.briday = dateStr;
            [weakSelf.TableView reloadData];
        };
        _dateview.hideblock = ^{
            [weakSelf hidehere];
        };
    }
    [self.view addSubview:_dateview.buttonbg];
    [self.view addSubview:_dateview];
    
    [UIView animateWithDuration:0.3 animations:^{
        self->_dateview.frame = CGRectMake(0, RECERHEIGHT-270, RECRWITCH, 270);
        self->_dateview.buttonbg.alpha=0.1;
    }];
}

- (void)hidehere{
    [UIView animateWithDuration:0.3 animations:^{
        self->_dateview.frame = CGRectMake(0, RECERHEIGHT, RECRWITCH, 270);
        self->_dateview.buttonbg.alpha=0.0;
    }];
}

- (UIButton *)DoneButton{
    if (!_DoneButton) {
        _DoneButton           = [[UIButton alloc] initWithFrame:CGRectMake(20, 35, RECRWITCH-40, 43)];
        _DoneButton.layer.cornerRadius  = 6;
        _DoneButton.layer.masksToBounds = YES;
        [_DoneButton setTitle:@"提交修改" forState:UIControlStateNormal];
        [_DoneButton.titleLabel setFont:[UIFont boldSystemFontOfSize:17]];
        [_DoneButton addTarget:self action:@selector(go_done) forControlEvents:UIControlEventTouchUpInside];
        [_DoneButton setBackgroundImage:[JonesClass createImageWithColor:Buttoncolor] forState:UIControlStateNormal];
        [_DoneButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
    return _DoneButton;
}

-(void) go_done{
    [SVProgressHUD showWithStatus:@"更新资料..."];
    if (Change_img) {
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
        NSString *url_img = [NSString stringWithFormat:@"000News/%@.png",[JonesClass generateUuidString]];
        [AliyunUploadBlock AliyunUploadimg:Change_img imgname:url_img finished:^(OSSTask * _Nonnull task, NSString * _Nonnull imgurl) {
            if (imgurl) {
                
                [self change_user:imgurl];
                lin_im_url = imgurl;
                
            }else{
                [SVProgressHUD showErrorWithStatus:@"上传头像失败"];
            }
        }];
        
    }else{
        [self change_user:_HereUserModel.logo];
    }
}


- (void)change_user:(NSString *)logo{
    NSMutableDictionary *diclin = [NSMutableDictionary new];
    
    [diclin setValue:_HereUserModel.phone forKey:@"phone"];
    if (_HereUserModel.password.length>0) {
        [diclin setValue:_HereUserModel.password forKey:@"password"];
    }else{
        [diclin setValue:[DEFAULTS objectForKey:@"password"] forKey:@"password"];
    }
    [diclin setValue:_HereUserModel.name forKey:@"name"];
    [diclin setValue:_HereUserModel.briday forKey:@"briday"];
    [diclin setValue:logo forKey:@"logo"];
    if ([_HereUserModel.sex isEqualToString:@"False"]) {
        [diclin setValue:@"0" forKey:@"sex"];
    }else{
        [diclin setValue:@"1" forKey:@"sex"];
    }
    
    ChangeUDataVModel *viewmodel = [[ChangeUDataVModel alloc] init:diclin];
    viewmodel.delegate=self;
}

- (void)Succes:(int)value dic:(nonnull NSDictionary *)dic{
    if (value==1) {
        [self goback];
    }else{
        [AliyunUploadBlock AliyunDelete:lin_im_url finished:^(OSSTask * _Nonnull task) {
            if (task.error) {
            }
        }];
    }
}




-(void)clickImge{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle: UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *imagepicker=[[UIImagePickerController alloc] init];
        imagepicker.delegate = self;
        imagepicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagepicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        imagepicker.allowsEditing = YES;
        if(AppsystemVersion.doubleValue >=12.0) {
            UIView *linview= [[UIView alloc] initWithFrame:CGRectMake(0, 0, RECRWITCH, NAV_Height-40)];
            linview.backgroundColor=[UIColor whiteColor];
            [imagepicker.view addSubview:linview];
            imagepicker.navigationBar.backgroundColor = [UIColor whiteColor];
        }
        [self presentViewController:imagepicker animated:YES completion:NULL];
    }];
    UIAlertAction *archiveAction = [UIAlertAction actionWithTitle:@"相机拍照" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        imagePicker.allowsEditing = YES;
        [self presentViewController:imagePicker animated:YES completion:NULL];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:deleteAction];
    [alertController addAction:archiveAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *) info{
    
    UIImage *img;
    
    if(picker.sourceType==UIImagePickerControllerSourceTypeCamera){
        img=[info objectForKey:UIImagePickerControllerEditedImage];
    }else{
        img=[info objectForKey:UIImagePickerControllerEditedImage];
    }
    
    UIImage *newImg=[HiJonesClass compressImage:img toByte:400];
    [self saveImage:newImg WithName:[NSString stringWithFormat:@"%@%@",[JonesClass generateUuidString],@".jpg"]];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    NSData* imageData = UIImagePNGRepresentation(tempImage);
    
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    
    NSString* documentsDirectory = [paths objectAtIndex:0];
    
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    
    [imageData writeToFile:fullPathToFile atomically:NO];
    
    if([fullPathToFile isEqualToString:@""]){
        [SVProgressHUD showErrorWithStatus:@"图片处理错误"];
    }else{
        
        Change_img = tempImage;
        [self.TableView reloadData];
    }
}

@end
